package com.gopay.checkorder.service.impl.expay;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.checkorder.service.BankOrderService;
import com.gopay.checkorder.service.task.BankCountDownLatch;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.BisBankInterfaceChannel;
import com.gopay.common.constants.bank.SpdbConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.dayend.BaseDayendEntry;
import com.gopay.common.domain.bank.spdb.adpay.SpdbAdPayBody;
import com.gopay.common.domain.bank.spdb.adpay.SpdbAdPayHeader;
import com.gopay.common.domain.bank.spdb.adpay.SpdbAdPayMessage;
import com.gopay.common.domain.bank.spdb.adpay.res.SinCutQueryRes;
import com.gopay.common.domain.bank.spdb.expay.SpdbMessageExPay;
import com.gopay.common.domain.cashier.BankCardType;
import com.gopay.common.domain.cps.vo.CheckOrderResult;
import com.gopay.common.domain.cps.vo.InAccInfo;
import com.gopay.common.util.DateUtils;
import com.gopay.common.util.TransUtil;
import com.gopay.remote.bank.ExPayInteractRemoteService;

/**
 * 
 * @ClassName: CheckOrdersPDBAdPayImpl 
 * @Description: 浦发代扣订单查询
 * @author ShenJun 
 * @date 2016年11月3日 下午1:54:53
 */
public class CheckOrderSpdbAdPayImpl implements BankOrderService {
    private final static Logger logger = LoggerFactory.getLogger("SPDB");
    @Resource(name = "bankExPayClient")
    private ExPayInteractRemoteService bankExPayClient;

    @Override
    public CheckOrderResult checkOrder(BankOrder bankOrder, String arg1) {
        CheckOrderResult checkOrderResult = new CheckOrderResult();
        checkOrderResult.setSuccess(false);
        checkOrderResult.setOrderId(bankOrder.getOrderId());

        SpdbMessageExPay base = new SpdbMessageExPay();
		base.setOrderId(bankOrder.getOrderId());
		base.setOutOrderId(bankOrder.getOutOrderId());
		base.setBank(bankOrder.getBankCode());
		base.setBankIntrChann(BisBankInterfaceChannel.get(bankOrder.getInterfaceChennelCode()));
		base.setBankBusProd(BisBankBusinessProd.get(bankOrder.getBankBizProdCode()));
		base.setOrderDate(DateUtils.format(bankOrder.getSendBankTm(), "yyyyMMddHHmmss"));

        Result result = new Result();
        try {
        	if(bankOrder.getBankBizProdCode().equals(BisBankBusinessProd._12.value)){
        		checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5041);
            	return checkOrderResult;
            }
            result = bankExPayClient.queryOrder(base);
            if (result == null || !result.isSuccess()) {
                logger.error("bankExPayClient fail.");
                if (result == null || ProcCodeConstants.PROC_CODE_100E6058.equals(result.getResultCode())) {
                    BankCountDownLatch.failIncrease(bankOrder.getBankCode());
                }
                checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
                checkOrderResult.setErrMsg("系统返回对账结果为空");
                return checkOrderResult;
            }
SinCutQueryRes res = (SinCutQueryRes) result.getDefaultModel();
            
            if (res == null) {
                // 查询结果为空
                logger.error("fail:orderId:" + bankOrder.getOrderId() + " errcode:"
                        + ProcCodeConstants.PROC_CODE_100E6022 + " err:bis query is null.");
                checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
                checkOrderResult.setErrMsg("银行返回对账结果为空");
                return checkOrderResult;
            }

            if (SpdbConstants.SPDB_ADPAY_RESPCODE_SUCCESS.equals(res.getRespCode())
                    || SpdbConstants.SPDB_ADPAY_RESPCODE_END.equals(res.getRespCode())) {
                // 交易成功
                checkOrderResult.setSuccess(true);
                InAccInfo accInfo = new InAccInfo();
                accInfo.setOrderId(bankOrder.getOrderId());
//                String amt = TransUtil.amountConvert2Yuan(res.getRealTransAmount());
                String amt = res.getRealTransAmount();
                accInfo.setAmount(new BigDecimal(amt));
                accInfo.setRetCode("00");
                accInfo.setCardType(BankCardType.Unknown.toString());
                checkOrderResult.setAccInfo(accInfo);
                logger.error("浦发代扣支付订单：" + bankOrder.getOrderId() + "的交易成功" + "返回码：" + res.getRespCode()
                        + "返回信息：" + res.getRespDesc());
            } else if (SpdbConstants.SPDB_ADPAY_RESPCODE_PROCESSING.equals(res.getRespCode())) {
//                    checkOrderResult.setBankFailure(true);
                checkOrderResult.setErrMsg("银行返回交易处理中");
                logger.error("浦发代扣支付订单：" + bankOrder.getOrderId() + "的交易处理中" + "返回码：" + res.getRespCode()
                        + "返回信息：" + res.getRespDesc());
            } else if (SpdbConstants.SPDB_ADPAY_RESPCODE_NOTEXIST.equals(res.getRespCode())) {
//              checkOrderResult.setBankFailure(true);
                checkOrderResult.setErrMsg("银行返回交易不存在");
                logger.error("浦发代扣支付订单：" + bankOrder.getOrderId() + "的交易不存在" + "返回码：" + res.getRespCode()
                      + "返回信息：" + res.getRespDesc());
            } else {
                checkOrderResult.setErrMsg("银行返回交易未知");
                logger.error("浦发代扣支付订单：" + bankOrder.getOrderId() + "的交易未知，系统暂不处理" + "返回码：" + res.getRespCode()
                        + "返回信息：" + res.getRespDesc());
            }
            return checkOrderResult;
        } catch (Exception e) {
            logger.error(bankOrder.getOrderId() + ": bankExPayClient fail.", e);
            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
            checkOrderResult.setErrMsg("浦发代扣对账异常");
            return checkOrderResult;
        }
    }

    public static void main(String[] args) {
        System.out.println(TransUtil.amountConvert2Yuan("111.1"));
    }
    @Override
    public BankOrder getDbOrder() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public BaseMessage dayend(String bank_bus) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Result getDayendMsg(String string) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List<CheckOrderResult> checkDayend(String bank_bus) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public CheckOrderResult checkDayendOrder(BaseDayendEntry bdm, BankOrder bo) {
        // TODO Auto-generated method stub
        return null;
    }

}
